#!/bin/bash

# AI伙伴后端服务启动脚本
# 作者: AI伙伴团队
# 日期: 2024-01-20

echo "==================================="
echo "AI伙伴后端服务启动脚本"
echo "==================================="

# 检查Java环境
if ! command -v java &> /dev/null; then
    echo "❌ Java未安装或未配置环境变量"
    exit 1
fi

JAVA_VERSION=$(java -version 2>&1 | awk -F '"' '/version/ {print $2}' | awk -F '.' '{print $1}')
if [ "$JAVA_VERSION" -lt 17 ]; then
    echo "❌ 需要Java 17或更高版本，当前版本: $JAVA_VERSION"
    exit 1
fi

echo "✅ Java环境检查通过"

# 检查Maven环境
if ! command -v mvn &> /dev/null; then
    echo "❌ Maven未安装或未配置环境变量"
    exit 1
fi

echo "✅ Maven环境检查通过"

# 检查MySQL连接
echo "🔍 检查MySQL连接..."
if command -v mysql &> /dev/null; then
    if mysql -h localhost -u root -p123456 -e "USE ai_partner;" 2>/dev/null; then
        echo "✅ MySQL连接正常"
    else
        echo "⚠️  MySQL连接失败，请检查数据库配置"
        echo "   确保MySQL服务已启动并创建了ai_partner数据库"
    fi
else
    echo "⚠️  MySQL客户端未安装，跳过连接检查"
fi

# 检查Redis连接
echo "🔍 检查Redis连接..."
if command -v redis-cli &> /dev/null; then
    if redis-cli ping 2>/dev/null | grep -q "PONG"; then
        echo "✅ Redis连接正常"
    else
        echo "⚠️  Redis连接失败，请检查Redis服务状态"
    fi
else
    echo "⚠️  Redis客户端未安装，跳过连接检查"
fi

# 选择启动方式
echo ""
echo "请选择启动方式："
echo "1. 开发模式启动 (mvn spring-boot:run)"
echo "2. 生产模式启动 (打包后运行jar)"
echo "3. Docker启动"
echo "4. 仅编译打包"
echo ""
read -p "请输入选项 (1-4): " choice

case $choice in
    1)
        echo "🚀 开发模式启动..."
        mvn spring-boot:run -Dspring-boot.run.profiles=dev
        ;;
    2)
        echo "📦 编译打包..."
        mvn clean package -DskipTests
        if [ $? -eq 0 ]; then
            echo "🚀 生产模式启动..."
            java -jar target/ai-partner-backend-*.jar --spring.profiles.active=prod
        else
            echo "❌ 编译失败"
            exit 1
        fi
        ;;
    3)
        echo "🐳 Docker启动..."
        if command -v docker-compose &> /dev/null; then
            docker-compose up -d
            echo "✅ Docker服务已启动"
            echo "📊 查看服务状态: docker-compose ps"
            echo "📋 查看日志: docker-compose logs -f ai-partner-backend"
        else
            echo "❌ Docker Compose未安装"
            exit 1
        fi
        ;;
    4)
        echo "📦 编译打包..."
        mvn clean package -DskipTests
        if [ $? -eq 0 ]; then
            echo "✅ 编译完成，jar包位于 target/ 目录"
        else
            echo "❌ 编译失败"
            exit 1
        fi
        ;;
    *)
        echo "❌ 无效选项"
        exit 1
        ;;
esac

echo ""
echo "==================================="
echo "🎉 启动完成！"
echo ""
echo "📖 API文档: http://localhost:8080/api/doc.html"
echo "🏥 健康检查: http://localhost:8080/api/actuator/health"
echo "📊 应用监控: http://localhost:8080/api/actuator/metrics"
echo ""
echo "如有问题，请查看日志文件: logs/ai-partner.log"
echo "==================================="
